package com.agang.sms.service.impl;

import com.agang.sms.service.SendSms;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: jiagang
 * @DateTime: 2020/5/16 16:48
 */
@Service
public class SendSmsImpl implements SendSms {

    @Override
    public boolean send(String phoneNum, String templateCode, Map<String, Object> code) {

        //连接阿里云获取配置
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4FzBqRhbWFXQt1XFotmC", "密码");
        IAcsClient client = new DefaultAcsClient(profile);

        //构建请求
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com"); //不要动
        request.setVersion("2017-05-25"); //不要动
        request.setAction("SendSms");

        //自定义的参数（手机号，验证码，签名，模板）
        request.putQueryParameter("PhoneNumbers", phoneNum);
        request.putQueryParameter("SignName", "迷迭香学习网站");
        request.putQueryParameter("TemplateCode", templateCode);

        //构建一个短信验证码
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("code",2233);
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(code));


        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return response.getHttpResponse().isSuccess();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}
